package com.example.mymusic;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

/**
 * @author xky
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ListView listView;
    private RelativeLayout relativeLayout;
    private ArrayList<Music> listMusic;
    private final String tag = "MainActivity";
    private MyReceiver myReceiver;
    private ImageView btnPlay;
    private ImageView musicImage;
    private TextView song;
    private TextView singer;
    private static final int NOT_MUSIC = -1;
    public static boolean mMainActivity = false;
    private MyConnection conn = null;
    private MusicService.MyBinder musicService = null;
    MySqLiteOpenHelper helper;
    private int index = -1;


    public int queryPosition(Context context){
        helper = new MySqLiteOpenHelper(context, "media_player_data.db", null, 1);
        SQLiteDatabase sqliteDatabase = helper.getReadableDatabase();
        //position_data 建表时 = -1
        @SuppressLint("Recycle")
        Cursor cursor = sqliteDatabase.query("media_player_table", new String[]{"id", "position_data"}, "id=?", new String[]{"1"}, null, null, null);
        int positionOriginalMethod = 0;
        while (cursor.moveToNext()) {
            positionOriginalMethod = cursor.getInt(cursor.getColumnIndex("position_data"));
        }
        return positionOriginalMethod;
    }

    private class MyConnection implements ServiceConnection {

        /**
         * 绑定成功后调用,获取到service
         */
        @RequiresApi(api = Build.VERSION_CODES.Q)
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(tag, "onServiceConnected: ");
            /*绑定后获得实例并更新界面
            MusicService.MyBinder对象，我们通过这个对象来操作服务中的方法*/
            musicService = (MusicService.MyBinder) service;
            update();
        }

        /**
         * Service 被破坏了或者被杀死的时候调用
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    @SuppressLint("WrongConstant")
    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.music_list);
        //申请权限
        requestPermission();

        //注册广播接收器
        myReceiver = new MyReceiver();
        //动态注册意图过滤器
        //检查接收到的广播的intent对象是否与过滤器相匹配，匹配则调用onReceive()接收
        IntentFilter intentFilter = new IntentFilter();
        //收到update_ui广播时调用
        intentFilter.addAction("update_ui");
        registerReceiver(myReceiver, intentFilter);

        //代表MainActivity被创建了
        mMainActivity = true;
        this.registerForContextMenu(listView);


        if (MusicService.mediaPlayer == null) {
            if (!MusicActivity.mMusicActivity){
                helper = new MySqLiteOpenHelper(MainActivity.this, "media_player_data.db", null, 1);
                SQLiteDatabase sqliteDatabase = helper.getWritableDatabase();
                sqliteDatabase.execSQL("update media_player_table set position_data=-1 where id=1");
                Log.e("改动数据:", "改position值为-1");
                sqliteDatabase.execSQL("update media_player_table set player_state_data=0 where id=1");
                Log.e("改动数据:", "改media_player_state_data_original值为0=false");
            }

        }

        queryPosition(this);

    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onResume() {
        super.onResume();
        //每次本activity弹回栈顶的时候，有权限就刷新一下歌曲
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            update();
        }
        helper = new MySqLiteOpenHelper(this, "media_player_data.db", null, 1);
        SQLiteDatabase sqliteDatabase1 = helper.getReadableDatabase();
        sqliteDatabase1.execSQL("update media_player_table set main_activity_data=1 where id=1");
    }


    @Override
    protected void onStop(){
        super.onStop();
        helper = new MySqLiteOpenHelper(this, "media_player_data.db", null, 1);
        SQLiteDatabase sqliteDatabase1 = helper.getReadableDatabase();
        sqliteDatabase1.execSQL("update media_player_table set main_activity_data=0 where id=1");
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    public void init() {
        Log.i(tag, "init: ");
        //初始化，绑定视图，设置点击事件监听
        listView = findViewById(R.id.logic_lv);
        listMusic = new ArrayList<>();
        listMusic = Utils.getMusic(this);

        relativeLayout = findViewById(R.id.local_music_bottom_rv);
        relativeLayout.setVisibility(View.GONE);

        ImageView btnPre = findViewById(R.id.local_music_bottom_iv_last);
        btnPre.setOnClickListener(this);


        btnPlay = findViewById(R.id.local_music_bottom_iv_play);
        btnPlay.setOnClickListener(this);


        ImageView btnNext = findViewById(R.id.local_music_bottom_iv_next);
        btnNext.setOnClickListener(this);


        musicImage = findViewById(R.id.local_music_bottom_iv_icon);
        musicImage.setOnClickListener(this);


        song = findViewById(R.id.local_music_bottom_tv_song);
        song.setOnClickListener(this);
        song.setSelected(true);


        singer = findViewById(R.id.local_music_bottom_tv_singer);

        //给ListView添加点击事件，实现点击哪首音乐就进行播放
        listView.setOnItemClickListener((parent, view, position, id) -> {
            Bundle bundle = new Bundle();
            bundle.putInt("position", position);
            Intent intent = new Intent();
            intent.putExtras(bundle);
            //跳转并将信息送去MusicActivity
            intent.setClass(MainActivity.this, MusicActivity.class);
            startActivity(intent);
        });

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                index = position;
                Log.e("被长按了：", String.valueOf(index));
                return false;
            }
        });

    }


    @Override
    @RequiresApi(api = Build.VERSION_CODES.Q)
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

        menu.add(0, 1, Menu.NONE, "播放");
        menu.add(0, 2, Menu.NONE, "删除");

    }

    @Override
    @RequiresApi(api = Build.VERSION_CODES.Q)
    public boolean onContextItemSelected(MenuItem item) {

        int id = item.getItemId();
        listMusic = new ArrayList<>();
        listMusic = Utils.getMusic(this);
        Music music = listMusic.get(index);

        if (id == 1) {

            Bundle bundle = new Bundle();
            bundle.putInt("position", index);
            Intent intent = new Intent();
            intent.putExtras(bundle);
            //跳转并将信息送去MusicActivity
            intent.setClass(MainActivity.this, MusicActivity.class);
            startActivity(intent);

        } else {
            listMusic = Utils.getMusic(this);
            music = listMusic.get(index);
            File file = new File(music.path);
            listMusic = Utils.getMusic(this);

            deleteMedieFile(file,this);
            Log.e("2222", String.valueOf(music.name));
            update();
        }
        return super.onOptionsItemSelected(item);

    }
    private void  deleteMedieFile(File file,Context mContext){
        if (file.isFile()) {
            String filePath = file.getPath();

            String TAG = "1111";
            if(filePath.endsWith(".mp3")){
                int res = mContext.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                        MediaStore.Audio.Media.DATA + "= \"" + filePath+"\"",
                        null);
                if (res>0){
                    file.delete();
                }else{
                    Log.e(TAG, "删除文件失败");
                }
            }else{
                file.delete();
            }
            //删除多媒体数据库中的数据
            return;
        }

    }

    @SuppressLint("NonConstantResourceId")
    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    public void onClick(View v) {
        //底部按钮点击事件，相应的调用service中的播放方法
        switch (v.getId()) {
            case R.id.local_music_bottom_iv_last:

                musicService.preMusic();
                break;
            case R.id.local_music_bottom_iv_play:

                musicService.playPause();
                break;
            case R.id.local_music_bottom_iv_next:

                musicService.nextMusic();
                break;

            //点击这里的话，就带着本首歌的信息去详情界面
            case R.id.local_music_bottom_iv_icon:
                Intent startIntent = new Intent();
                Bundle startBundle = new Bundle();
                startBundle.putParcelableArrayList("listMusic", listMusic);
                startBundle.putInt("position", musicService.getMPosition());
                startIntent.putExtras(startBundle);
                startIntent.setClass(MainActivity.this, MusicActivity.class);
                startActivity(startIntent);
                return;
            default:
                break;
        }

    }


    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void update() {
        Log.i(tag, "update: ");
        //更新一遍歌曲列表
        listMusic = new ArrayList<>();
        listMusic = Utils.getMusic(this);
        MyAdapter myAdapter = new MyAdapter(listMusic);

        SQLiteDatabase sqliteDatabase = helper.getReadableDatabase();
        //position_data 建表时 = -1
        @SuppressLint("Recycle")
        Cursor cursor = sqliteDatabase.query("media_player_table", new String[]{"id", "position_data", "player_state_data"}, "id=?", new String[]{"1"}, null, null, null);
        int positionOriginalMethod = 0;
        while (cursor.moveToNext()) {
            positionOriginalMethod = cursor.getInt(cursor.getColumnIndex("position_data"));
        }

        if (positionOriginalMethod != NOT_MUSIC) {
            if (conn != null) {
                if (musicService != null) {
                    //绑定了服务，可以调用服务中的方法
                    song.setText(musicService.getListMusic().get(musicService.getMPosition()).name);
                    singer.setText(musicService.getListMusic().get(musicService.getMPosition()).singer);
                    Log.i(tag, "调用到了");
                    if (musicService.getMusicState()) {
                        btnPlay.setImageResource(R.drawable.pause);
                    } else {
                        btnPlay.setImageResource(R.drawable.start);
                    }
                    musicImage.setImageBitmap(musicService.getBitmap());
                } else {
                    //没有调用到onServiceConnected，不能调用服务里的方法只能用.
                    song.setText(MusicService.listMusic.get(positionOriginalMethod).name);
                    singer.setText(MusicService.listMusic.get(positionOriginalMethod).singer);
                    Log.i(tag, "没有调用到");
                    if (MusicService.musicState) {
                        btnPlay.setImageResource(R.drawable.pause);
                    } else {
                        btnPlay.setImageResource(R.drawable.start);
                    }
                    musicImage.setImageBitmap(MusicService.bitmap);
                }
                relativeLayout.setVisibility(View.VISIBLE);
            } else {
                //没绑定服务呢,启动服务并绑定
                conn = new MyConnection();
                Log.i(tag, "第一次走这里");
                //传递歌曲的信息给MusicService
                Intent intent = new Intent(this, MusicService.class);
                Bundle bundle = new Bundle();
                //在第一个Activity中创建序列化对象(MainActivity.java)
                //将Music类型的链表放置在bundle中
                //还有歌曲位置
                bundle.putInt("position", positionOriginalMethod);
                //再把bundle放置在intent中
                intent.putExtras(bundle);
                //开启服务，版本高就用前台服务，低就可以用普通服务
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startForegroundService(intent);
                } else {
                    startService(intent);
                }
                //绑定服务
                bindService(intent, conn, BIND_AUTO_CREATE);
            }
        }
        listView.setAdapter(myAdapter);

        //用于设置特殊样式
        if (positionOriginalMethod != NOT_MUSIC) {
            listView.setSelection(positionOriginalMethod);
        }
    }


    /**
     * 回调函数，申请权限后回调onRequestPermissionResult函数
     * 第一个参数为请求码，第二个参数是刚刚请求的权限集，第三个参数是请求结果，0表示授权成功，-1表示授权失败
     */

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        //申请完成的回调提示被拒绝的权限
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0) {
                for (int i = 0; i < grantResults.length; i++) {
                    int grantResult = grantResults[i];
                    if (grantResult == PackageManager.PERMISSION_DENIED) {
                        String s = permissions[i];
                        Toast.makeText(this, s + "权限被拒绝了", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
        init();
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void requestPermission() {
        Log.i(tag, "requestPermission");
        //判断是否含有权限，无就将读与写的权限先定义到静态字符数组中
        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.INTERNET);
        }

        if (!permissionList.isEmpty()) {
            //如果数组不空，即有需要申请的权限就调用这个动态申请权限的代码
            ActivityCompat.requestPermissions(this, permissionList.toArray(new String[0]), 1);
        } else {
            init();
        }
    }

    public class MyReceiver extends BroadcastReceiver {
        public MyReceiver() {


        }


        @RequiresApi(api = Build.VERSION_CODES.Q)
        @Override
        public void onReceive(Context context, Intent intent) {

            //收到update_ui广播时调用update更新界面
            String action = intent.getAction();
            String updateUi = "update_ui";
            if (updateUi.equals(action)) {
                update();
            }
        }
    }

    class MyAdapter extends BaseAdapter {
        private ArrayList<Music> list;
        private final int NOT_SELECT = 0;

        public MyAdapter(ArrayList<Music> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public int getItemViewType(int position) {
            int flag = NOT_SELECT;
            if (MusicService.m_position == position) {
                flag = 1;
            }
            return flag;
        }

        /**
         * 获取该条目要显示的界面，convertView旧视图，被隐藏掉的视图，parent是父级视图，也就是ListView之类的
         */
        @SuppressLint({"InflateParams", "SetTextI18n"})
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            MyHolder holder;
            int type = getItemViewType(position);
            holder = new MyHolder();
            if (convertView == null) {
                if (type == NOT_SELECT) {
                    convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_local_music, null);
                } else {
                    convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_selected, null);
                    TextView musicState = convertView.findViewById(R.id.item_local_music_state);
                    musicState.setText(MusicService.musicState ? R.string.play : R.string.pause);
                }

                holder.tName = convertView.findViewById(R.id.music_item_title_tv);
                holder.tSinger = convertView.findViewById(R.id.music_item_artist_tv);
                holder.tDuration = convertView.findViewById(R.id.item_local_music_duration);

                holder.tId = convertView.findViewById(R.id.music_item_idd);

                holder.tName.setSelected(type != NOT_SELECT);

                //convertView为空即第一次绘制listView，初始化一个convertView的实例，并将holder设置到Tag中
                convertView.setTag(holder);
            } else {

                //convertView不为空则直接取出来，实现复用convertView
                holder = (MyHolder) convertView.getTag();
            }
            holder.tName.setText(list.get(position).name);
            holder.tSinger.setText(list.get(position).singer);
            String time = Utils.formatTime(list.get(position).duration);
            holder.tDuration.setText(time);
            holder.tId.setText(position + 1 + "");


            return convertView;
        }

        /**
         * 用来标记控件
         */

        class MyHolder {
            TextView tName, tSinger, tDuration, tId;

        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(tag, "onDestroy: ");
        //取消广播接收器
        unregisterReceiver(myReceiver);
        if (conn != null) {
            Log.i(tag, "onDestroy: unbindService");
            unbindService(conn);
        }
        mMainActivity = false;
    }


}
